package com.econ.powercloud.ems.timing.report.prometheus.callback;

import com.econ.powercloud.console.facade.utils.CacheKeyUtils;
import com.econ.powercloud.ems.common.util.JacksonExtUtil;
import com.econ.powercloud.ems.util.AsyncHttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 每秒执行命令数
 */
@Component
public class PrometheusRedisCommandTotalCallback implements AsyncHttpClientUtil.StringFutureCallback{

    final private String category = "redis";

    final private String itemTemplate = "%sTotal";

    final private String instanceKey = "data.result[0].metric.instance";

    final private String cmdKey = "data.result[0].metric.cmd";

    final private String valueKey = "data.result[0].value[1]";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void success(String content) {
        Map<String, String> prometheusResult = JacksonExtUtil.flatJsonToMap(content);
        if(!prometheusResult.containsKey(instanceKey)){
            return;
        }
        String instance = (String)prometheusResult.get(instanceKey).replaceAll(":", "-");
        String cmdType = (String)prometheusResult.get(cmdKey);
        String item = String.format(itemTemplate, cmdType);
        String value = prometheusResult.get(valueKey);
        String redisKey = CacheKeyUtils.getMonitorDataKey(instance, category);
        HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
        hashOperations.put(redisKey, item, value);
    }
}
